package com.lube.support;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.lube.handler.ServerHandler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * 连接管理
 * 
 * @author caizhiping
 * @date 2017年2月10日 上午10:57:09
 */
public class ChannelManager {

	private static final Logger LOG = LogManager.getLogger(ChannelManager.class);
	/**
	 * clientId与channel映射
	 */
	private final static ConcurrentMap<String, Channel> channels = new ConcurrentHashMap<String, Channel>();

	/**
	 * 添加连接
	 * 
	 * @param clientId
	 * @param channel
	 */
	public static void add(String clientId, Channel channel) {
		Channel oldChannel = channels.put(clientId, channel);
		if (oldChannel != null) {
			oldChannel.close();
		}

		/**
		 * 侦听连接关闭后移除缓存的连接
		 */
		channel.closeFuture().addListener(new ChannelFutureListener() {
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {

					Channel chn = future.channel();
					String cliId = chn.attr(ServerHandler.SENDER).get().getClientId();

					// 移除连接
					remove(cliId);

					LOG.info("客户端[{}]连接断开,移除客户端连接.", cliId);
				}
			}

		});
	}

	/**
	 * 获取连接
	 * 
	 * @param clientId
	 * @return
	 */
	public static Channel get(String clientId) {
		return channels.get(clientId);
	}

	/**
	 * 移除连接
	 * 
	 * @param clientId
	 */
	public static void remove(String clientId) {
		channels.remove(clientId);
	}
}
